#!/bin/bash

# Soul Jigsaw AppImage 打包脚本

set -e

APP_NAME="soul-jigsaw"
# 从版本文件读取当前版本号
VERSION_FILE="VERSION"
if [ -f "$VERSION_FILE" ]; then
    CURRENT_VERSION=$(cat "$VERSION_FILE")
else
    CURRENT_VERSION="1.0.0"
fi

# 自增版本号（仅增加修订版本号）
VERSION_PARTS=(${CURRENT_VERSION//./ })
MAJOR=${VERSION_PARTS[0]}
MINOR=${VERSION_PARTS[1]}
PATCH=${VERSION_PARTS[2]}
NEW_PATCH=$((PATCH + 1))
APP_VERSION="$MAJOR.$MINOR.$NEW_PATCH"

# 更新版本文件
echo "$APP_VERSION" > "$VERSION_FILE"

APP_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="$APP_DIR/AppDir"
PYTHON_VERSION="3.9.16"

echo "开始打包 $APP_NAME AppImage，版本: $APP_VERSION..."

# 清理之前的构建
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# 下载并安装 Python AppImage
echo "下载 Python AppImage..."
wget -c "https://github.com/niess/python-appimage/releases/download/python${PYTHON_VERSION}/python${PYTHON_VERSION}-cp39-cp39-manylinux2014_x86_64.AppImage" \
     -O "$BUILD_DIR/python.AppImage"
chmod +x "$BUILD_DIR/python.AppImage"

# 提取 Python AppImage
echo "提取 Python AppImage..."
cd "$BUILD_DIR"
./python.AppImage --appimage-extract >/dev/null
mv squashfs-root usr

# 安装应用依赖
echo "安装应用依赖..."
./usr/bin/python3 -m pip install --no-cache-dir \
    PyQt5 \
    opencv-python \
    pillow \
    pyyaml \
    numpy \
    tensorflow-cpu \
    diffusers

# 复制应用源代码
echo "复制应用源代码..."
cp -r "$APP_DIR/src" "$BUILD_DIR/usr/src"
cp -r "$APP_DIR/config" "$BUILD_DIR/usr/config"
cp "$APP_DIR/main.py" "$BUILD_DIR/usr/"
cp "$APP_DIR/README.md" "$BUILD_DIR/usr/"

# 创建启动脚本
cat > "$BUILD_DIR/AppRun" << 'EOF'
#!/bin/bash
HERE="$(dirname "$(readlink -f "${0}")")"
export PYTHONPATH="${HERE}"/usr/src:${PYTHONPATH}
exec "${HERE}"/usr/bin/python3 "${HERE}"/usr/main.py "$@"
EOF
chmod +x "$BUILD_DIR/AppRun"

# 创建桌面文件
cat > "$BUILD_DIR/$APP_NAME.desktop" << EOF
[Desktop Entry]
Name=Soul Jigsaw
Comment=AI驱动的拼图游戏，帮助玩家通过完成拼图来探索内心世界
Exec=AppRun
Icon=$APP_NAME
Type=Application
Categories=Game;LogicGame;
Terminal=false
EOF

# 创建图标文件 (使用默认图标)
mkdir -p "$BUILD_DIR/usr/share/icons/hicolor/256x256/apps"
cp "$BUILD_DIR/usr/share/icons/hicolor/256x256/apps/python.png" \
   "$BUILD_DIR/usr/share/icons/hicolor/256x256/apps/$APP_NAME.png" || true

# 下载 AppImageTool
echo "下载 AppImageTool..."
wget -c "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage" \
     -O appimagetool.AppImage
chmod +x appimagetool.AppImage

# 创建 AppImage
echo "创建 AppImage..."
./appimagetool.AppImage "$BUILD_DIR" -n

echo "打包完成: $APP_NAME-$APP_VERSION-x86_64.AppImage"